Lesson 3 - intermediate exercise
Read the code in each section and do the following -
- Add comments to explain the code
- Suggest test data to test the code
- Make the suggested changes.
The answers will only say what the code does and how to make the suggested change. Note - The code in these examples are using python I/O
filename = "test.txt"
names = ["bob", "sally", "fred"]
# open file in write mode
fileRef = open(filename, "w")
fileRef.writeLines(names)
fileRef.close()
Suggested change - Create two files. One to store names the other to store a-team quotes.
Toggle answer
file = open("test.txt")
while file:
text = file.readline()
print "line 1 - ", text
file.close()
Suggested changes Test to see if a line is equal to the text "Spud". If it is then print out "yay i found a spud!"
Toggle answer
file = open("test.txt", "r")
output = []
for line in file.readlines():
words = line.split()
temp = ""
for i in words:
temp = temp + "ug" + i
output.append(temp)
file.close()
file = open("ugtest.txt", "w")
file.writelines(output)
file.close()
Suggested changes - Count the number of words seen in the file opened.